#include "./app_task.h"
#include "./handler_task.h"
#include "./make_ice_task.h"
#include "./status_task.h"
#include "./draw_task.h"
#include "../pub_driver/cmd_can.h"
#include "../ice_driver/ctrl.h"
#include "../ice_driver/sensor.h"
#include "../xlib/rcc.h"

namespace ice_task {

AppTask appTask;

using namespace pub_driver;
using namespace ice_driver;

static void event_loop();

void AppTask::run() {
    stm32f1::rcc::use_swd();
    cmdCAN.init();
    ctrl.init();
    sensor.init();
    statusTask.start();
    handlerTask.init_start();
    makeIceTask.init_start();
    drawTask.init_start();
    println("ice run");
    event_loop();
}

using namespace conn;

static void handle_fast_req(const Frame &frame) {

    cmdCAN.ack(frame);
    cmdCAN.ipcReceiver.recv_next(frame.len);
    handlerTask.post(frame);
}

static void handle_query(const Frame &frame) {
    switch (frame.seq_cmd()) {
        case proto::pub::QUERY_TASK_INFO: {
            const TaskInfo &taks_info = handlerTask.task_info;
            cmdCAN.result(frame, taks_info.seq,taks_info.cmd);
        }; break;

    }
}

static void event_loop() {
    Frame frame;

    for (;;) {
        cmdCAN.ipcReceiver.recv_from(frame);
        switch (frame.type()) {
            case type::PING: cmdCAN.pong(frame); break;
            case type::FAST_REQ: handle_fast_req(frame); break;
            case type::QUERY: handle_query(frame); break;
        }
    }
}

}
